﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using BLL.Installer;
using BLL.Interface.Menu;
using BLL.Model.Menu;
using System.Data;
using BLL.DbAccess;
using BLL.Utility;
using Castle.Core.Logging;

namespace BLL.Implement.Menu
{
    public class MenuInfoImpl : IMenuInfo
    {
        public ILogger Logger { get; set; }
        private readonly DefaultContext _defaultContext;
        private readonly DbSet<MenuInfo> _menuInfoContext;

        public MenuInfoImpl()
        {
            _defaultContext = ContainerHelper.Instance.Container.Resolve<DefaultContext>();
            _menuInfoContext = _defaultContext.MenuInfoContext;
        }

        public bool AddMenuInfo(MenuInfo menuInfo)
        {
            _menuInfoContext.Add(menuInfo);
            _defaultContext.SaveChanges();
            Logger.InfoFormat("新增了一条记录：{0}", menuInfo);
            return true;
        }

        public bool UpdateMenuInfo(MenuInfo menuInfo)
        {
            var oldInfo = FindMenuInfoById(menuInfo.Id, true);
            CopyProperties.Compare(oldInfo, menuInfo, new List<string> { "Id,Order" });
            _defaultContext.SaveChanges();
            Logger.InfoFormat("更新了一条记录：{0}", oldInfo);
            return true;
        }

        public bool DeleteMenuInfoById(int id)
        {
            var menuInfo = FindMenuInfoById(id, true);
            if (menuInfo == null)
            {
                Logger.FatalFormat("删除失败：没有找到编号为{0}的记录", id);
                return false;
            }
            _menuInfoContext.Remove(menuInfo);
            _defaultContext.SaveChanges();
            Logger.InfoFormat("删除了一条记录：{0}", menuInfo);
            return true;
        }

        public bool DeleteAllMenuInfo()
        {
            const string sql = "delete from MenuInfo";
            try
            {
                _defaultContext.Database.ExecuteSqlCommand(sql);
                return true;
            }
            catch (Exception e)
            {
                Logger.FatalFormat("删除所有记录失败，SQL：{0}，错误{1}", sql, e.Message);
                return false;
            }
        }

        public bool ReOrder(int id1, int id2)
        {
            var menu1 = FindMenuInfoById(id1, true);
            var menu2 = FindMenuInfoById(id2, true);
            var temp = menu1.Order;
            menu1.Order = menu2.Order;
            menu2.Order = temp;
            _defaultContext.SaveChanges();
            Logger.InfoFormat("交换了顺序：{0}：{1}", menu1.Name, menu2.Name);
            return true;
        }

        public IList<MenuInfo> GetAllMenuInfo()
        {
            return _menuInfoContext.AsNoTracking().OrderBy(p => p.Order).ThenBy(p => p.Id).ToList();
        }

        public MenuInfo FindMenuInfoById(int id, bool tracking)
        {
            return tracking
                       ? _menuInfoContext.Find(id)
                       : _menuInfoContext.AsNoTracking().FirstOrDefault(p => p.Id == id);
        }

        public IList<MenuInfo> GetMenuInfoByFilter(dynamic condition, Tuple<string, string> sort, PageInfo page)
        {
            var query = _menuInfoContext.AsNoTracking().AsQueryable();

            sort = new Tuple<string, string>("order", "asc");

            if (page != null)
            {
                page.TotalRecords = query.Count();
                return query.OrderBy(sort.Item1, sort.Item2).ThenBy("Id")
                                            .Skip(page.PageSize * (page.CurrentPage - 1))
                                            .Take(page.PageSize).ToList();
            }
            return query.ToList();
        }

        public bool AddMenuInfo(IList<MenuInfo> menuInfoList)
        {
            try
            {
                foreach (var entry in menuInfoList)
                {
                    _menuInfoContext.Add(entry);
                }
                int count = _defaultContext.SaveChanges();
                Logger.InfoFormat("{0}条记录被插入。", count);
                return true;
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                return false;
            }
        }

        public bool DeleteMenuInfoById(IList<int> menuInfoList)
        {
            try
            {
                foreach (int id in menuInfoList)
                {
                    var entryToDelete = FindMenuInfoById(id, true);
                    _menuInfoContext.Remove(entryToDelete);
                }
                int count = _defaultContext.SaveChanges();
                Logger.InfoFormat("{0}条记录被删除。", count);
                return true;
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                return false;
            }
        }

    }

}
